package visiopuce.action;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import visiopuce.ICommandIds;
import visiopuce.objets.Personne;
import visiopuce.service.PrescriptionServiceImpl;
import visiopuce.ui.DossierEditorInput;
import visiopuce.ui.view.DossierEditor;

public class RecupererPrescriptionAction extends Action {

	public RecupererPrescriptionAction(String text) {
		super(text);

		// The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_RECUPERER_PRESCRIPTION);
		// Associate the action with a pre-defined command, to allow key
		// bindings.
		setActionDefinitionId(ICommandIds.CMD_RECUPERER_PRESCRIPTION);
		setText("Recupérer les prescriptions");
		setImageDescriptor(visiopuce.Activator.getImageDescriptor("/icons/download.png"));
	}

	public void run() {
		Personne personne = PrescriptionServiceImpl.getInstance().parsePrescription();
		if (personne != null) {
			MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Traitement terminé", "Enregistrement terminé pour le patient :" + personne.getNom());
			IEditorInput editorInput = new DossierEditorInput(personne.getIdPersonne());
			try {
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(editorInput, DossierEditor.ID, true, IWorkbenchPage.MATCH_INPUT);
			} catch (PartInitException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			IEditorPart editeurActif = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
			if (editeurActif instanceof DossierEditor) {
				DossierEditor editeur = (DossierEditor) editeurActif;
				if (editeur.getDossierTabItem() != null) {
					editeur.getTabFolder().setSelection(editeur.getDossierTabItem().getTabItem());
				}
			}
		} else {
			MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Traitement terminé", "Echec!");

		}
	}
}